package cc.ipost.ipost;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import cc.ipost.ipost.data.RequestData;

import com.umeng.analytics.MobclickAgent;

@SuppressLint({ "HandlerLeak", "HandlerLeak" })
public class HistoryActivity extends Activity {

	ProgressDialog loadingDialog;
	ListView hListView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		this.setContentView(R.layout.history);

		hListView = (ListView) findViewById(R.id.historylist);
		loadingDialog = new ProgressDialog(this);
		loadingDialog.setMessage("Loading....");
		View homebtn = this.findViewById(R.id.navhome_btn);
		homebtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent in = new Intent(HistoryActivity.this, MainActivity.class);
				HistoryActivity.this.startActivity(in);

			}
		});

		updateInfo();

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			loadingDialog.dismiss();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("get cards info fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(HistoryActivity.this).setMessage(msgs)
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.ERR: {
				Log.e("get cards info err", msg.toString());
				new AlertDialog.Builder(HistoryActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("get cards info success", msg.toString());
				try {
					JSONArray cards = ((JSONObject) msg.obj)
							.getJSONArray("cards");
					initView(cards);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				System.out.println(msg.obj);
			}
			}

		}
	};
	
	protected Handler delHandler = new Handler(){
		
		public void handleMessage(Message msg) {
			loadingDialog.dismiss();
			switch (msg.what) {
			case MySettings.FAIL: {
				Log.e("del card fail", msg.toString());
				String msgs = "Something went wrong, please try again later.";
				if (msg != null && msg.obj != null) {
					msgs = msg.obj.toString();
				}
				new AlertDialog.Builder(HistoryActivity.this).setMessage(msgs)
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.ERR: {
				Log.e("del card err", msg.toString());
				new AlertDialog.Builder(HistoryActivity.this)
						.setMessage(msg.obj.toString())
						.setNegativeButton("OK", null).setCancelable(true)
						.show();
				break;
			}
			case MySettings.SUCCESS: {
				Log.e("del card success", msg.toString());
				updateInfo();
			}
			}

		}
		
	};

	private void updateInfo() {
		MyApplication ma = (MyApplication) this.getApplication();
		if (ma.user == null) {
			Intent i = new Intent(this, AccountActivity.class);
			this.startActivity(i);
		}
		loadingDialog.show();
		RequestData rd = new RequestData(String.format(MySettings.UCARD,
				ma.user.ID), RequestData.GET);

		WebServiceTask wst = new WebServiceTask(rd, handler);
		wst.execute("");
	}

	private void initView(JSONArray cards) throws JSONException {
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < cards.length(); i++) {
			JSONObject card = cards.getJSONObject(i);
			HashMap<String, Object> map = new HashMap<String, Object>();
			Long unixLong = card.getLong("date_created");
			unixLong *= 1000;
			SimpleDateFormat fmd = new SimpleDateFormat("dd/MM/yy");
			SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
			String date = "";
			String time = "";
			try {
				date = fmd.format(unixLong);
				time = fmt.format(unixLong);
			} catch (Exception ex) {

			}
			map.put("date", date);
			map.put("time", time);
			map.put("cover", card.getString("cover_thumb"));
			map.put("id", card.getString("id"));
			map.put("cover_big", card.getString("cover"));
			int sta = card.getInt("status");
			int[] statusRes = {R.string.pending, R.string.verifing, R.string.verified, R.string.failed, R.string.success};
			String status = getString(statusRes[sta]);
			map.put("status", status);
			JSONObject rec = card.getJSONObject("receiver");
			map.put("receiver", rec.getString("fname"));
			map.put("text", card.getString("text"));
			listItem.add(map);
		}
		HistoryAdapter ha = new HistoryAdapter(this, listItem);
		hListView.setAdapter(ha);
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

}
